package org.zyj.io.example.case5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebsocketServer {

    private final int port;

    public WebsocketServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)//
                    .channel(NioServerSocketChannel.class)//
                    .option(ChannelOption.SO_BACKLOG, 128)//
                    .option(ChannelOption.SO_KEEPALIVE, true)//
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //基于http协议, 使用http的编码和解码器
                            pipeline.addLast(new HttpServerCodec());
                            //以块的方式写, 添加 ChunkedWriteHandler
                            pipeline.addLast(new ChunkedWriteHandler());

                            //http数据在传输过程中是分段的, HttpObjectAggregator, 就是可以将多个段聚合
                            //这就是为什么, 当浏览器发送大量数据时, 就会发出多次http请求
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /*
                            对于websocket, 它的数据是以 帧(frame)的形式传递
                            可以看到WebSocketFrame下面有6个子类
                            浏览器请求时: ws://localhost:7000/hello 表示请求的uri
                            WebSocketServerProtocolHandler 核心功能是将 http协议升级为ws协议, 保持长连接
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

                            //自定义的handler, 处理业务逻辑
                            pipeline.addLast(new MyTextWebSocketFrameHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("服务器启动: 端口监听成功");
                } else {
                    System.out.println("服务器启动: 端口监听失败");
                }
            });
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new WebsocketServer(7000).run();
    }
}
